var webSocketInit = function(){
    if(!window.wsServer)
    {
        window.WebSocket = window.WebSocket || window.MozWebSocket;
        if(!window.WebSocket){
            return;
        }
        window.wsServer = new WebSocket(window.wsServerAddress);
        window.wsServer.onmessage = function(evt){
            var data = JSON.parse(evt.data);
            switch(data.cmd)
            {
                case "client_unlogin":
                    modalAlert(lang('client_unlogin'));
                    break;
                case "report_read_card":
                    if(data.args.cardData)
                    {
                        if(data.args.isCancel)
                        {
                            ajaxRequest('/Home/Order/queryRFData', {
                                'hotel':window.currentHotel,
                                'cardData':data.args.cardData,
                                'isCancel':1
                            }, 'post', function(cardInfo) {
                                showRFInfo(cardInfo.data);
                                window.serialNum = cardInfo.data.id;
                                $('#cancelledModal').modal('show');
                            }, function(error) {
                                if(error.responseJSON.status == 512){
                                    RFCardError(106);
                                }
                            });
                        }else{
                            readRfCard(data.args.cardData);
                        }
                    }
                    else
                    {
                        //应用程序已有提示
                        //modalAlert(lang('RF.6'));
                    }
                    break;
            }
    
            hideCardLoading();
        };
    }
};
$(function() {
    window.checkintime = parseInt($('#hour-room-init').data('checkintime'));
    window.checkouttime = parseInt($('#hour-room-init').data('checkouttime'));
    var initAddOrderModal = function(roomId, selectedDateFormat) {
        showAddOrderModal(roomId, selectedDateFormat);
    };
    var showAddOrderModal = function(roomId, selectedDateFormat) {
        window.discountrule = '';
        window.discount = '';
        window.discountHourrule = '';
        window.discountHour = '';
        window.discountLongrule = '';
        window.discountLong = '';
        var selectedDate = getDate(selectedDateFormat);
        // 初始化入住房间
        $('#addOrderRoom').html(createAddRoomTemplate(roomId, selectedDate, selectedDateFormat));
        $('#addOrderHourRoom').html(createAddHourRoomTemplate(roomId, selectedDate, selectedDateFormat));
        $('#addOrderLongRoom').html(createAddLongRoomTemplate(roomId, selectedDate, selectedDateFormat));
        $('#addOrderRoom .addOrderTableRoom').eq(0).find('.addOrderUserTr').eq(0).find('.orderUserMobile').attr('data-first', 0);
        $('#addOrderHourRoom .addOrderHourTableRoom').eq(0).find('.addOrderHourUserTr').eq(0).find('.orderHourUserMobile').attr('data-first', 0);
        $('#addOrderLongRoom .addOrderLongTableRoom').eq(0).find('.addOrderLongUserTr').eq(0).find('.orderLongUserMobile').attr('data-first', 0);
        // 初始化收款
        $('#addOrderReceive tbody').html(createAddReceiveTemplate(roomId));
        $('#addOrderHourReceive tbody').html(createAddHourReceiveTemplate(roomId));
        $('#addOrderLongReceive tbody').html(createAddLongReceiveTemplate(roomId));
        // 根据日期，初始化脚步按钮，修改modal头名称
        var modalTitle = $('#addModal .modal-title');
        var days = selectedDate.getDays(today);
        var bookBtn = $('#submitBook');
        var oldBookBtn = $('#submitBookOld');
        var checkInBtn = $('#submitCheckIn');
        var bookHourBtn = $('#submitHourBook');
        var oldBookHourBtn = $('#submitHourBookOld');
        var checkInHourBtn = $('#submitHourCheckIn');
        var bookLongBtn = $('#submitLongBook');
        var oldBookLongBtn = $('#submitLongBookOld');
        var checkInLongBtn = $('#submitLongCheckIn');
        if(days < 0) {
            bookBtn.addClass('hidden');
            checkInBtn.addClass('hidden');
            oldBookBtn.removeClass('hidden');
            bookHourBtn.addClass('hidden');
            checkInHourBtn.addClass('hidden');
            oldBookHourBtn.removeClass('hidden');
            bookLongBtn.addClass('hidden');
            checkInLongBtn.addClass('hidden');
            oldBookLongBtn.removeClass('hidden');
            modalTitle.html(lang('order.additional'));
        } else {
            if(days === 0) {
                bookBtn.removeClass('hidden');
                checkInBtn.removeClass('hidden');
                oldBookBtn.addClass('hidden');
                bookHourBtn.removeClass('hidden');
                checkInHourBtn.removeClass('hidden');
                oldBookHourBtn.addClass('hidden');
                bookLongBtn.removeClass('hidden');
                checkInLongBtn.removeClass('hidden');
                oldBookLongBtn.addClass('hidden');
                modalTitle.html(lang('order.add'));
            } else {
                bookBtn.removeClass('hidden');
                checkInBtn.addClass('hidden');
                oldBookBtn.addClass('hidden');
                bookHourBtn.removeClass('hidden');
                checkInHourBtn.addClass('hidden');
                oldBookHourBtn.addClass('hidden');
                bookLongBtn.removeClass('hidden');
                checkInLongBtn.addClass('hidden');
                oldBookLongBtn.addClass('hidden');
                modalTitle.html(lang('order.add'));
            }
        }
        formInlineRight($('#submitBook'));
        formInlineRight($('#submitCheckIn'));
        formInlineRight($('#submitBookOld'));
        formInlineRight($('#submitHourBook'));
        formInlineRight($('#submitHourCheckIn'));
        formInlineRight($('#submitHourBookOld'));
        formInlineRight($('#submitLongBook'));
        formInlineRight($('#submitLongCheckIn'));
        formInlineRight($('#submitLongBookOld'));
        calculateAddReceiveTotal();
        calculateAddHourReceiveTotal();
        calculateAddLongReceiveTotal();
        var addModal = $('#addModal');
        addModal.data('roomId', roomId).data('daysType', days).data('selectedDateFormat', selectedDateFormat).find('#bookRemark').val('');
        addModal.modal('show');
    };
    $('#addOrderRoom').on('click','.areaCode>.dropdown-menu li>a',function(){
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_code_cookie") != 'undefined') {
            $.cookie('area_code_cookie', value, { expires: 7, path: '/' });
        }
        window.discountrule = '';
        window.discount = '';
    });
    $('#addOrderHourRoom').on('click','.areaCode>.dropdown-menu li>a',function(){
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_code_cookie") != 'undefined') {
            $.cookie('area_code_cookie', value, { expires: 7, path: '/' });
        }
        window.discountHourrule = '';
        window.discountHour = '';
    });  
    $('#addOrderLongRoom').on('click','.areaCode>.dropdown-menu li>a',function(){
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_code_cookie") != 'undefined') {
            $.cookie('area_code_cookie', value, { expires: 7, path: '/' });
        }
        window.discountLongrule = '';
        window.discountLong = '';
    }); 
    var areaCodeValue = function(){
      var areaCode;
      if ($.cookie("area_code_cookie") != 'undefined') {
          areaCode = $.cookie("area_code_cookie");
          if (areaCode != undefined) {
              $('.areaCode').find('.areaCodeValue').text(areaCode);
          } else {
              $('.areaCode').find('.areaCodeValue').text('86');
          }
      } 
    }
    var createAddReceiveTemplate = function(roomId) {
        var receiveTemplate = $($('#templateAddOrderReceive').clone().html());
        if(roomId !== undefined) {
            var roomItem = window.roomItemType[roomId];
            receiveTemplate.find('.addOrderReceive').attr('value', '');
        }
        return receiveTemplate.prop('outerHTML');
    };
    var createAddHourReceiveTemplate = function(roomId) {
        var receiveTemplate = $($('#templateAddOrderHourReceive').clone().html());
        if(roomId !== undefined) {
            var roomItem = window.roomItemType[roomId];
            receiveTemplate.find('.addOrderHourReceive').attr('value', '');
        }
        return receiveTemplate.prop('outerHTML');
    };
    var createAddLongReceiveTemplate = function(roomId) {
        var receiveTemplate = $($('#templateAddOrderLongReceive').clone().html());
        if(roomId !== undefined) {
            var roomItem = window.roomItemType[roomId];
            receiveTemplate.find('.addOrderLongReceive').attr('value', '');
        }
        return receiveTemplate.prop('outerHTML');
    };
    var createAddRoomTemplate = function(roomId, selectedDate, selectedDateFormat) {
        var startDate = getDate($('#datePicker').data('start'));
        var roomItem = window.roomItemType[roomId];
        var roomTemplate = $($('#templateAddOrderRoom').clone().html());
        var userTemplate = $($('#templateAddOrderUser').clone().html());
        var dateList = '';
        var changeDate;
        for(var i = 0; i < 31; i++) {
            changeDate = startDate.customDays(i).customFormat();
            if(changeDate === selectedDateFormat) {
                dateList += '<li data-value="' + changeDate + '" class="active"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            } else {
                dateList += '<li data-value="' + changeDate + '"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            }
        }
        roomTemplate.find('.addOrderRoomCheckInMenu').html(dateList);
        roomTemplate.find('.addOrderRoomCheckIn').attr('data-value', selectedDateFormat);
        roomTemplate.find('.addOrderRoomCheckIn .info').html(selectedDateFormat);
        roomTemplate.find('.addOrderRoomIdMenu li[data-value="' + roomId + '"]').addClass('active');
        roomTemplate.find('.addOrderRoomId').attr('data-value', roomId);
        roomTemplate.find('.addOrderRoomId .info').html(roomItem.name);
        roomTemplate.find('.addOrderPrice').attr('value', calculateRoomPrice(selectedDateFormat, roomId, 1));
        return '<table class="table addOrderTable addOrderTableRoom"><tbody>' + roomTemplate.prop('outerHTML') + userTemplate.prop('outerHTML') + '</tbody></table><div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addUser text-primary">'+lang("addCohabit")+'</div></div></div>';
    };
    var createAddHourRoomTemplate = function(roomId, selectedDate, selectedDateFormat) {
        var startDate = getDate($('#datePicker').data('start'));
        var roomItem = window.roomItemType[roomId];
        var roomHourTemplate = $($('#templateAddOrderHourRoom').clone().html());
        var userHourTemplate = $($('#templateAddOrderHourUser').clone().html());
        var dateHourList = '';
        var dateminuteList = '';
        var changeHourDate;
        var getHours = parseInt(new Date().getHours());
        var getMinutes = parseInt(new Date().getMinutes());
        if(getMinutes<10){
           getMinutes = '0'+getMinutes 
        }
        window.presenttime = getHours+':'+getMinutes;
        roomHourTemplate.find('#_contents .dropdown_hour .info').html(getHours);
        for(var i = 0; i < 24; i++) {
            if(i < 10) {
                i = '0' + i;
            } 
            dateHourList += '<li data-value="' + i + '"><a href="javascript:void(0);">' + i + '</a></li>';
        }
        roomHourTemplate.find('#_contents .dropdown_hour ul').html(dateHourList);
        for(var j = 0; j < 60; j++) {
            if(j < 10) {
                j = '0' + j;
            } 
            dateminuteList += '<li data-value="' + j + '"><a href="javascript:void(0);">' + j + '</a></li>';
        }
        roomHourTemplate.find('#_contents .dropdown_minute ul').html(dateminuteList);     
        
        var timestamp = parseInt((new Date(selectedDateFormat.replace(new RegExp(/-/g), '/'))).getTime() / 1000);
        var hourprice = window.hourprice[roomId + '_' + timestamp];
        if(hourprice){
            for(var i=0;i<hourprice.length;i++){
                roomHourTemplate.find('.addOrderRoomHourMenu').append('<li data-value="'+hourprice[i]+'"><a href="javascript:void(0);">'+hourprice[i]+lang("hour")+'</a></li>');
            }
            roomHourTemplate.find('.addOrderRoomHour').attr('data-value',hourprice[0]).find('.info').text(hourprice[0]+lang("hour"));
            roomHourTemplate.find('.addOrderHourPrice').attr('value', calculateHourRoomPrice(selectedDateFormat, roomId, 2));
        }      
        roomHourTemplate.find('.addOrderHourRoomCheckIn').attr('data-value', window.presenttime);
        roomHourTemplate.find('.addOrderHourRoomCheckIn').attr('data-time', selectedDateFormat);
        roomHourTemplate.find('.addOrderHourRoomCheckIn .info').html(window.presenttime);
        roomHourTemplate.find('.addOrderHourRoomIdMenu li[data-value="' + roomId + '"]').addClass('active');
        roomHourTemplate.find('.addOrderHourRoomId').attr('data-value', roomId);
        roomHourTemplate.find('.addOrderHourRoomId .info').html(roomItem.name);
        return '<table class="table addOrderHourTable addOrderHourTableRoom"><tbody>' + roomHourTemplate.prop('outerHTML') + userHourTemplate.prop('outerHTML') + '</tbody></table><div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addHourUser text-primary">'+lang("addCohabit")+'</div></div></div>';
    };
    //时间
    $('#addModal').on('click','.addOrderHourRoomCheckIn',function(e){
        e.stopPropagation();
        e.preventDefault();
        timeSelectContainer = $(this).closest('.time-select-container').find('.time-container');
        if(timeSelectContainer.hasClass('hidden')){
            timeSelectContainer.removeClass('hidden');
        }else{
            timeSelectContainer.addClass('hidden');
        }
    }).on('click','.clear_time',function(e){
        e.stopPropagation();
        e.preventDefault();
        _contents = $(this).closest('#_contents');
        _contents.closest('.time-container').addClass('hidden');
    }).on('click','.select_time',function(e){
        e.stopPropagation();
        e.preventDefault();
        _contents = $(this).closest('#_contents');
        var hour = _contents.find('.dropdown_hour .info').text();
        var minute = _contents.find('.dropdown_minute .info').text();
        if(hour!=''&& minute!=''){
            _contents.closest('.time-select-container').find('.addOrderHourRoomCheckIn .info').text(hour+':'+minute);
        }
        _contents.closest('.time-container').addClass('hidden');
    });
    var createAddLongRoomTemplate = function(roomId, selectedDate, selectedDateFormat) {
        var startDate = getDate($('#datePicker').data('start'));
        var roomItem = window.roomItemType[roomId];
        var roomLongTemplate = $($('#templateAddOrderLongRoom').clone().html());
        var userLongTemplate = $($('#templateAddOrderLongUser').clone().html());
        var dateLongList = '';
        var changeLongDate;
        for(var i = 0; i < 31; i++) {
            changeLongDate = startDate.customDays(i).customFormat();
            if(changeLongDate === selectedDateFormat) {
                dateLongList += '<li data-value="' + changeLongDate + '" class="active"><a href="javascript:void(0);">' + changeLongDate + '</a></li>';
            } else {
                dateLongList += '<li data-value="' + changeLongDate + '"><a href="javascript:void(0);">' + changeLongDate + '</a></li>';
            }
        }        
        roomLongTemplate.find('.addOrderLongRoomCheckInMenu').html(dateLongList);
        roomLongTemplate.find('.addOrderLongRoomCheckIn').attr('data-value', selectedDateFormat);
        roomLongTemplate.find('.addOrderLongRoomCheckIn .info').html(selectedDateFormat);
        roomLongTemplate.find('.addOrderLongRoomIdMenu li[data-value="' + roomId + '"]').addClass('active');
        roomLongTemplate.find('.addOrderLongRoomId').attr('data-value', roomId);
        roomLongTemplate.find('.addOrderLongRoomId .info').html(roomItem.name);
        roomLongTemplate.find('.addOrderLongPrice').attr('value', calculateLongRoomPrice(selectedDateFormat, roomId, 1));
        return '<table class="table addOrderLongTable addOrderLongTableRoom"><tbody>' + roomLongTemplate.prop('outerHTML') + userLongTemplate.prop('outerHTML') + '</tbody></table><div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addLongUser text-primary">'+lang("addCohabit")+'</div></div></div>';
    };
    var createOrderSuccess = function(data) {
        var orderInfo = data.data;
        for(var i = 0; i < orderInfo.length; i++) {
            window.orderList.unshift(orderInfo[i]);
        }
        $('#addModal').modal('hide');
        $('#doc').trigger('refresh.meizhu');
        hideMainLoading();
        var initContent = $('#orderInitContent');
        initContent.data('value', orderInfo[0].id);
        initContent.data('parent', orderInfo[0].order);
        initContent.data('roomid', orderInfo[0].room);
        ajaxRequest('/Home/Order/getOrder', {
            "hotel":window.currentHotel,
            "order":orderInfo[0].order
        }, 'post', initOrderInfoSuccess, function(error) {
            hideMainLoading();
        });         
    };
    
    var createOrderError = function(data, obj) {
        hideMainLoading();
        if(typeof data.responseJSON == 'undefined') {
            formInlineTip(obj,lang('tip.networkPoor'), 0);
        } else {
            formInlineTip(obj, data.responseJSON.info, 0);
        }
        if(data.responseJSON.status == 308) {
            $('#checkoutDirtyModal').show();
            var dirtyTip = $('#checkoutDirtyModal .modal-body');
            dirtyTip.find('li').remove();
            var infoStatus = data.responseJSON.data.orderRoomInfos;
            var infoDirty = data.responseJSON.data.roomInfos;
            var vipCard = data.responseJSON.data.vipCard;
            if(infoDirty) {
                for(var i = 0; i < infoDirty.length; i++) {
                    dirtyTip.append($('<li/>').text(infoDirty[i].roomName + lang('Dirty.1')));
                }
            }
            if(infoStatus) {
                for(var i = 0; i < infoStatus.length; i++) {
                    dirtyTip.append($('<li/>').text(infoStatus[i].roomName + lang('Dirty.2')));
                }
            }
            $('#confirmEnterBtnL').on('click', function() {
                if(window.roomStyle){
                    var params = getHourOrderParams();
                }else if(window.longStyle){
                    var params = getLongOrderParams();
                }else{
                    var params = getOrderParams();
                }
                if(vipCard){
                    params.vipCard = vipCard;
                }
                params.checkIn = 0;
                showMainLoading();
                ajaxRequest('/Home/Order/orderCheckIn', params, 'post',createOrderSuccess, createOrderError,obj);
                $('#checkoutDirtyModal').hide();
            });
            $('#cancelEnterBtnL').unbind('click').bind('click', function() {
                $('#checkoutDirtyModal').hide();
            });
        }
    };
    var isHourRoom = $('#isHourRoom');
    // 点击空的房间录入订单
    $('#orderListBody').on('click', '.order-item-td.without-order', function(e) {
        e.stopPropagation();
        if(!$(this).find('.maintain-icon').hasClass('hidden')){
            return false;
        }
        window.roomStyle = false;
        window.longStyle = false;
        $('#commonPanel').removeClass('hidden');
        $('#hourPanel').addClass('hidden');  
        $('#longPanel').addClass('hidden');  
        $('.common-room-foot').removeClass('hidden');
        $('.hour-room-foot').addClass('hidden');
        $('.long-room-foot').addClass('hidden');
        isHourRoom.find('.common-panel').addClass('is-active');
        isHourRoom.find('.hour-panel').removeClass('is-active');
        isHourRoom.find('.long-panel').removeClass('is-active');
        var orderItem = $(this);
        var roomId = orderItem.data('value');
        var selectedDateFormat = orderItem.data('date');
        initAddOrderModal(roomId, selectedDateFormat);
        isHourRoom.addClass('hidden');
        isHourRoom.find('.hour-panel').addClass('hidden');
        isHourRoom.find('.long-panel').addClass('hidden');
        if(orderItem.data('hourprice') || orderItem.data('longprice')) {
            isHourRoom.removeClass('hidden');
            if(orderItem.data('hourprice')){
                isHourRoom.find('.hour-panel').removeClass('hidden');
            }
            if(orderItem.data('longprice')){
                isHourRoom.find('.long-panel').removeClass('hidden');
            }
        } else {
            isHourRoom.addClass('hidden');
        }
    });
    //计算房间价格
    var calculateRoomPrice = function(date, room, night) {
        var total_price = 0;
        var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g), '/'))).getTime() / 1000);
        for(var i = 0; i < night; i++) {
            total_price += parseFloat(window.roomPrices[room + '_' + timestamp]);
            timestamp += 86400;
        }
        return total_price.toFixed(2);
    };
    //计算钟点房价格
    var calculateHourRoomPrice = function(date, room, hour) {
        var total_price = 0;
        var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g), '/'))).getTime() / 1000);
        for(var i=0;i<window.hourprice[room + '_' + timestamp].length;i++){
            if(window.hourprice[room + '_' + timestamp][i] == hour){
                total_price = window.hourpay[room + '_' + timestamp][i];
            }
        }
        return parseFloat(total_price).toFixed(2);      
    };
    //计算钟点房价格
    var calculateLongRoomPrice = function(date, room, longs) {
        var total_price = 0;
        var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g), '/'))).getTime() / 1000);
        for(var i = 0; i < longs; i++) {
            total_price += parseFloat(window.longprice[room + '_' + timestamp]);
        }
        return parseFloat(total_price).toFixed(2);      
    };
    //会员号码 
    $('#addModal').on('click', '.infoMoblie', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var submitMoblie = $(this).closest('.addLi');
        var param = {};
        var infoMoblietemplate = submitMoblie.closest('.vipPositive').find('.infoMoblietemplate');
        infoMoblietemplate.html('');
        param.hotel = window.currentHotel;
        param.vipInfoId = submitMoblie.find('.addMoblie').attr('vipInfoId');
        param.vipUserId = submitMoblie.find('.addMoblie').attr('vipUserId');
        ajaxRequest('/Home/Customer/vipInfo', param, 'post', function(data) {
            var searchInfo = data.data;
            var tooltipTemplate = $($('#templateVipMoblieTip').clone().html());
            tooltipTemplate.find('.levelName').html(searchInfo.levelName);
            tooltipTemplate.find('.name').html(searchInfo.name);
            tooltipTemplate.find('.mobile').html(searchInfo.mobile);
            tooltipTemplate.find('.identity').html(searchInfo.identity);
            tooltipTemplate.find('.checkin').html(searchInfo.checkin);
            tooltipTemplate.find('.totalAll').html(searchInfo.total);
            tooltipTemplate.find('.average').html(searchInfo.average);
            if(searchInfo.roomType){
                tooltipTemplate.find('.zuijin');
                tooltipTemplate.find('.roomType').html(lang('roomStyle')+searchInfo.roomType);
            }
            if(searchInfo.roomName){
                tooltipTemplate.find('.roomName').html(lang('roomNum')+searchInfo.roomName);
            }
            infoMoblietemplate.html(tooltipTemplate.prop('outerHTML')).removeClass('hidden');
        }, function(data) {

        });
    });   
    $('#addModal').click(function() {
        $('.infoMoblietemplate').addClass('hidden');
    });
    var getSearchMobile = function(mobile,type,obj){
        var vipMobile = obj.next('.vipMobile');
        var addOrderUserTr = obj.closest('.addOrderUserTr');
        var areaCode = addOrderUserTr.find('.areaCodeValue').text().trim();
        var param = {};
        param.hotel = window.currentHotel;
        param.mobile = mobile;
        param.areaCode = areaCode;
        ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
            var searchMobile = data.data;
            var isFirst = obj.data('first');
            if(type == 1){
                vipMobile.html('');
                if(searchMobile.length > 0) {
                    vipMobile.closest('.vipPositive').addClass('open');
                    vipMobile.prev('input').attr('data-toggle', "dropdown");
                    var vipMoblieTemplate = $($('#templateAddVipMoblie').clone().html());
                    var vipMoblieHTMl = '';
                    for(var i = 0; i < searchMobile.length; i++) {
                        vipMoblieTemplate.find('.addMoblie').attr({
                            'vipUserId': searchMobile[i].id,
                            'vipInfoId': searchMobile[i].vipinfo_id,
                            'mobile': searchMobile[i].mobile,
                        });
                        vipMoblieTemplate.find('.addMoblie').text(searchMobile[i].mobile);
                        vipMoblieHTMl += vipMoblieTemplate.prop('outerHTML');
                    }
                    vipMobile.append(vipMoblieHTMl);
                    vipMobile.find('li').eq(0).addClass('active');
                } else {
                    vipMobile.closest('.vipPositive').removeClass('open');
                    vipMobile.prev('input').removeAttr('data-toggle');
                }  
            }else if(type == 2){
                if(searchMobile.length > 0) {
                    if(isFirst == 0){
                        window.discountrule = searchMobile[0].discountrule;
                        window.discount = searchMobile[0].discount;  
                    };
                    addOrderUserTr.find('.orderUserName').val(searchMobile[0].name);
                    addOrderUserTr.find('.orderUserID').val(searchMobile[0].identity);
                    addOrderUserTr.find('.orderUserMobile').val(searchMobile[0].mobile);
                    window.vipMobile = searchMobile[0].mobile;
                }  
                calculateAddReceiveTotal();
            }
        }, function(data) {

        });
    };    
    var clearPrivilege = function(){
        var privilegeRoom = $('#addOrderRoom .addOrderTableRoom').eq(0);
        var mobile = privilegeRoom.find('.orderUserMobile').val();
        if(mobile != window.vipMobile) {
            $('#addModal .privilege').text('');
            window.discountrule = '';
            window.discount = '';  
            calculateAddReceiveTotal();
        }        
    };    
    var clearHourPrivilege = function(){
        var privilegeRoom = $('#addOrderHourRoom .addOrderHourTableRoom').eq(0);
        var mobile = privilegeRoom.find('.orderHourUserMobile').val();
        if(mobile != window.vipHourMobile) {
            $('#addModal .hour-privilege').text('');
            window.discountHourrule = '';
            window.discountHour = ''; 
            calculateAddHourReceiveTotal();
        }        
    };    
    var clearLongPrivilege = function(){
        var privilegeRoom = $('#addOrderLongRoom .addOrderLongTableRoom').eq(0);
        var mobile = privilegeRoom.find('.orderLongUserMobile').val();
        if(mobile != window.vipLongMobile) {
            $('#addModal .long-privilege').text('');
            window.discountLongrule = '';
            window.discountLong = '';
            calculateAddLongReceiveTotal();
        }        
    };
    $('#addModal').on('keyup', '.orderUserMobile', function() {
        clearPrivilege();
        var submitMoblie = $(this);
        var mobile = submitMoblie.val();
        var vipMobile = submitMoblie.next('.vipMobile');
        if(mobile.toString().length > 3) {
            getSearchMobile(mobile,1,submitMoblie);
        } else {
            vipMobile.closest('.vipPositive').removeClass('open');
            vipMobile.prev('input').removeAttr('data-toggle');
        }
    });
    $('#addModal').on('click', '.addLi', function(e) {
        e.preventDefault();
        var submitMoblie = $(this);
        var mobile = submitMoblie.find('.addMoblie').attr('mobile');
        var obj = submitMoblie.closest('.addOrderUserTr').find('.orderUserMobile')
        getSearchMobile(mobile,2,obj);
    });    
    $('#addModal').on('click', '.addHourLi', function(e) {
        e.preventDefault();
        var submitMoblie = $(this);
        var mobile = submitMoblie.find('.addHourMoblie').attr('mobile');
        var obj = submitMoblie.closest('.addOrderHourUserTr').find('.orderHourUserMobile');
        getSearchHourMobile(mobile,2,obj);
    });   
    //钟点房会员
    $('#addModal').on('click', '.infoHourMoblie', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var submitMoblie = $(this).closest('.addHourLi');
        var param = {};
        var infoMoblietemplate = submitMoblie.closest('.vipHourPositive').find('.infoHourMoblietemplate');
        infoMoblietemplate.html('');
        param.hotel = window.currentHotel;
        param.vipInfoId = submitMoblie.find('.addHourMoblie').attr('vipInfoId');
        param.vipUserId = submitMoblie.find('.addHourMoblie').attr('vipUserId');
        ajaxRequest('/Home/Customer/vipInfo', param, 'post', function(data) {
            var searchInfo = data.data;
            var tooltipTemplate = $($('#templateVipHourMoblieTip').clone().html());
            tooltipTemplate.find('.levelName').html(searchInfo.levelName);
            tooltipTemplate.find('.name').html(searchInfo.name);
            tooltipTemplate.find('.mobile').html(searchInfo.mobile);
            tooltipTemplate.find('.identity').html(searchInfo.identity);
            tooltipTemplate.find('.checkin').html(searchInfo.checkin);
            tooltipTemplate.find('.totalAll').html(searchInfo.total);
            tooltipTemplate.find('.average').html(searchInfo.average);
            if(searchInfo.roomType) {
                tooltipTemplate.find('.zuijin');
                tooltipTemplate.find('.roomType').html(lang('roomStyle') + searchInfo.roomType);
            }
            if(searchInfo.roomName) {
                tooltipTemplate.find('.roomName').html(lang('roomNum') + searchInfo.roomName);
            }
            infoMoblietemplate.html(tooltipTemplate.prop('outerHTML')).removeClass('hidden');
        }, function(data) {

        });
    });   
    $('#addModal').click(function() {
        $('.infoHourMoblietemplate').addClass('hidden');
    });
    var getSearchHourMobile = function(mobile,type,obj){
        var vipMobile = obj.next('.vipHourMobile');
        var addOrderHourUserTr = obj.closest('.addOrderHourUserTr');
        var areaCode = addOrderHourUserTr.find('.areaCodeValue').text().trim();
        var param = {};
        param.hotel = window.currentHotel;
        param.mobile = mobile;
        param.areaCode = areaCode;
        ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
            var searchMobile = data.data;
            var isFirst = obj.data('first');
            if(type == 1){
                vipMobile.html('');
                if(searchMobile.length > 0) {
                    vipMobile.closest('.vipHourPositive').addClass('open');
                    vipMobile.prev('input').attr('data-toggle', "dropdown");
                    var vipMoblieTemplate = $($('#templateAddVipHourMoblie').clone().html());
                    var vipMoblieHTMl = '';
                    for(var i = 0; i < searchMobile.length; i++) {
                        vipMoblieTemplate.find('.addHourMoblie').attr({
                            'vipUserId': searchMobile[i].id,
                            'vipInfoId': searchMobile[i].vipinfo_id,
                            'mobile': searchMobile[i].mobile,
                        });
                        vipMoblieTemplate.find('.addHourMoblie').text(searchMobile[i].mobile);
                        vipMoblieHTMl += vipMoblieTemplate.prop('outerHTML');
                    }
                    vipMobile.append(vipMoblieHTMl);
                    vipMobile.find('li').eq(0).addClass('active');
                } else {
                    vipMobile.closest('.vipHourPositive').removeClass('open');
                    vipMobile.prev('input').removeAttr('data-toggle');
                }  
            }else if(type == 2){
                if(searchMobile.length > 0) {
                    if(isFirst == 0){
                        window.discountHourrule = searchMobile[0].discountrule;
                        window.discountHour = searchMobile[0].discount;
                    };
                    addOrderHourUserTr.find('.orderHourUserName').val(searchMobile[0].name);
                    addOrderHourUserTr.find('.orderHourUserID').val(searchMobile[0].identity);
                    addOrderHourUserTr.find('.orderHourUserMobile').val(searchMobile[0].mobile);
                    window.vipHourMobile = searchMobile[0].mobile;
                }  
                calculateAddHourReceiveTotal();
            }
        }, function(data) {

        });
    };    
    $('#addModal').on('keyup', '.orderHourUserMobile', function() {
        clearHourPrivilege();
        var submitMoblie = $(this);
        var mobile = submitMoblie.val();
        var vipMobile = submitMoblie.next('.vipHourMobile');
        if(mobile.toString().length > 3) {
            getSearchHourMobile(mobile,1,submitMoblie);
        } else {
            vipMobile.closest('.vipHourPositive').removeClass('open');
            vipMobile.prev('input').removeAttr('data-toggle');
        }
    });
    $('#addModal').on('change', '.orderHourUserMobile', function() {
        clearHourPrivilege();
        var submitMoblie = $(this);
        vipMobile = submitMoblie.next('.vipHourMobile');
        var mobile = submitMoblie.val();
        var mobileLen = mobile.toString().length;
        if(mobileLen == 11) {
            getSearchHourMobile(mobile,2,submitMoblie);
        };
    });
    $('#addModal').on('click', '.addHourLi', function(e) {
        e.preventDefault();
        var submitMoblie = $(this);
        var mobile = submitMoblie.find('.addHourMoblie').attr('mobile');
        var obj = submitMoblie.closest('.addOrderHourUserTr').find('.orderHourUserMobile')
        getSearchHourMobile(mobile,2,obj);
    });
    //长租房会员
    $('#addModal').on('click', '.infoLongMoblie', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var submitMoblie = $(this).closest('.addLongLi');
        var param = {};
        var infoMoblietemplate = submitMoblie.closest('.vipLongPositive').find('.infoLongMoblietemplate');
        infoMoblietemplate.html('');
        param.hotel = window.currentHotel;
        param.vipInfoId = submitMoblie.find('.addLongMoblie').attr('vipInfoId');
        param.vipUserId = submitMoblie.find('.addLongMoblie').attr('vipUserId');
        ajaxRequest('/Home/Customer/vipInfo', param, 'post', function(data) {
            var searchInfo = data.data;
            var tooltipTemplate = $($('#templateVipHourMoblieTip').clone().html());
            tooltipTemplate.find('.levelName').html(searchInfo.levelName);
            tooltipTemplate.find('.name').html(searchInfo.name);
            tooltipTemplate.find('.mobile').html(searchInfo.mobile);
            tooltipTemplate.find('.identity').html(searchInfo.identity);
            tooltipTemplate.find('.checkin').html(searchInfo.checkin);
            tooltipTemplate.find('.totalAll').html(searchInfo.total);
            tooltipTemplate.find('.average').html(searchInfo.average);
            if(searchInfo.roomType) {
                tooltipTemplate.find('.zuijin');
                tooltipTemplate.find('.roomType').html(lang('roomStyle') + searchInfo.roomType);
            }
            if(searchInfo.roomName) {
                tooltipTemplate.find('.roomName').html(lang('roomNum') + searchInfo.roomName);
            }
            infoMoblietemplate.html(tooltipTemplate.prop('outerHTML')).removeClass('hidden');
        }, function(data) {

        });
    });   
    $('#addModal').click(function() {
        $('.infoLongMoblietemplate').addClass('hidden');
    });
    var getSearchLongMobile = function(mobile,type,obj){
        var vipMobile = obj.next('.vipLongMobile');
        var addOrderLongUserTr = obj.closest('.addOrderLongUserTr');
        var areaCode = addOrderLongUserTr.find('.areaCodeValue').text().trim();
        var param = {};
        param.hotel = window.currentHotel;
        param.mobile = mobile;
        param.areaCode = areaCode;
        ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
            var searchMobile = data.data;
            var isFirst = obj.data('first');
            if(type == 1){
                vipMobile.html('');
                if(searchMobile.length > 0) {
                    vipMobile.closest('.vipLongPositive').addClass('open');
                    vipMobile.prev('input').attr('data-toggle', "dropdown");
                    var vipMoblieTemplate = $($('#templateAddVipLongMoblie').clone().html());
                    var vipMoblieHTMl = '';
                    for(var i = 0; i < searchMobile.length; i++) {
                        vipMoblieTemplate.find('.addLongMoblie').attr({
                            'vipUserId': searchMobile[i].id,
                            'vipInfoId': searchMobile[i].vipinfo_id,
                            'mobile': searchMobile[i].mobile,
                        });
                        vipMoblieTemplate.find('.addLongMoblie').text(searchMobile[i].mobile);
                        vipMoblieHTMl += vipMoblieTemplate.prop('outerHTML');
                    }
                    vipMobile.append(vipMoblieHTMl);
                    vipMobile.find('li').eq(0).addClass('active');
                } else {
                    vipMobile.closest('.vipLongPositive').removeClass('open');
                    vipMobile.prev('input').removeAttr('data-toggle');
                }  
            }else if(type == 2){
                if(searchMobile.length > 0) {
                    if(isFirst == 0){
                        window.discountLongrule = searchMobile[0].discountrule;
                        window.discountLong = searchMobile[0].discount;
                    };
                    addOrderLongUserTr.find('.orderLongUserName').val(searchMobile[0].name);
                    addOrderLongUserTr.find('.orderLongUserID').val(searchMobile[0].identity);
                    addOrderLongUserTr.find('.orderLongUserMobile').val(searchMobile[0].mobile);
                    window.vipLongMobile = searchMobile[0].mobile;
                }  
                calculateAddLongReceiveTotal();
            }
        }, function(data) {

        });
    };    
    $('#addModal').on('keyup', '.orderLongUserMobile', function() {
        clearLongPrivilege();
        var submitMoblie = $(this);
        var mobile = submitMoblie.val();
        var vipMobile = submitMoblie.next('.vipHourMobile');
        if(mobile.toString().length > 3) {
            getSearchLongMobile(mobile,1,submitMoblie);
        } else {
            vipMobile.closest('.vipLongPositive').removeClass('open');
            vipMobile.prev('input').removeAttr('data-toggle');
        }
    });
    $('#addModal').on('change', '.orderLongUserMobile', function() {
        clearLongPrivilege();
        var submitMoblie = $(this);
        vipMobile = submitMoblie.next('.vipLongMobile');
        var mobile = submitMoblie.val();
        var mobileLen = mobile.toString().length;
        if(mobileLen == 11) {
            getSearchLongMobile(mobile,2,submitMoblie);
        };
    });
    $('#addModal').on('click', '.addLongLi', function(e) {
        e.preventDefault();
        var submitMoblie = $(this);
        var mobile = submitMoblie.find('.addLongMoblie').attr('mobile');
        var obj = submitMoblie.closest('.addOrderLongUserTr').find('.orderLongUserMobile')
        getSearchLongMobile(mobile,2,obj);
    });
    var calculateAddReceiveTotal = function() {
        var total = 0;
        var nights = 0;
        $('#addOrderRoom .addOrderPrice').each(function() {
            var val = $(this).val();
            if(val == '') {
                val = 0;
            }
            total += parseFloat(val);
            nights += parseInt($(this).closest('.addOrderRoomTr').find('#nights .info').text());
        });
        var receipt = 0;
        var deposit = 0;
        var otherConsume = 0;
        var privilege = total;
        var receivearr = [];
        $('#addOrderReceive .addOrderReceiveTr').each(function() {
            var isDeposit = $(this).find('.addOrderReceiveIsDeposit').data('value');
            var value = parseFloat($(this).find('.addOrderReceive').val());
            var type = $(this).find('.addOrderReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            $.each(data.data.transData, function (key, value) {
                var isDeposit = value.isDeposit;
                var value = parseFloat(value.value);
                var type = value.type;
                value = value > 0 ? value : 0;
                if(isDeposit == 1) {
                    deposit += value;
                } else if(isDeposit == 0){
                    receipt += value;
                }else{
                    if(type !== 0){
                        receipt += value;
                    }
                    otherConsume += value;
                }            
                if(window.discountrule != '') {
                    if(parseFloat(window.discount) == 0) {
                        privilege = ((total * window.discountrule * 100) / 1000);
                    } else {
                        privilege = (parseFloat(total) - parseFloat(window.discountrule) * parseInt(nights));
                    }
                    if(privilege < 0) {
                        privilege = 0;
                    }
                    $('#addModal').find('.privilege').html(lang('privilege') +window.symbols+ parseFloat(privilege+ otherConsume).toFixed(2));
                } else {
                    $('#addModal').find('.privilege').html('');
                }
                var overdue = privilege + otherConsume - receipt;
                overdue = overdue < 0 ? 0 : overdue;
                $('#addModal').find('.total').html(parseFloat(total + otherConsume).toFixed(2));
                $('#addModal').find('.receipt').html(receipt.toFixed(2));
                $('#addModal').find('.deposit').html(deposit.toFixed(2));
                $('#addModal').find('.overdue').html(overdue.toFixed(2));                
            });              
        }, null);  
    };
    //钟点房
    var calculateAddHourReceiveTotal = function() {
        var total = 0;
        var subtract = 0;
        $('#addOrderHourRoom .addOrderHourPrice').each(function() {
            var val = $(this).val();
            if(val == '') {
                val = 0;
            }
            total += parseFloat(val);
            subtract++;
        });
        var privilege = total;
        var receipt = 0;
        var deposit = 0;
        var otherConsume = 0;
        var receivearr = [];
        $('#addOrderHourReceive .addOrderHourReceiveTr').each(function() {
            var isDeposit = $(this).find('.addOrderHourReceiveIsDeposit').data('value');
            var value = parseFloat($(this).find('.addOrderHourReceive').val());
            var type = $(this).find('.addOrderHourReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyHourType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });        
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            $.each(data.data.transData, function (key, value) {
                var isDeposit = value.isDeposit;
                var value = parseFloat(value.value);
                var type = value.type;
                value = value > 0 ? value : 0;
                if(isDeposit == 1) {
                    deposit += value;
                } else if(isDeposit == 0){
                    receipt += value;
                } else{
                    if(type !== 0){
                        receipt += value;
                    }
                    otherConsume += value;
                }      
                if(window.discountHourrule != '') {
                    if(parseFloat(window.discountHour) == 0) {
                        privilege = ((total * window.discountHourrule * 100) / 1000);
                    } else {
                        privilege = (parseFloat(total) - parseFloat(window.discountHourrule)*parseInt(subtract));
                    }
                    if(privilege < 0) {
                        privilege = 0;
                    }
                    $('#addModal').find('.hour-privilege').html(lang('privilege') +window.symbols+ parseFloat(privilege+ otherConsume).toFixed(2));
                } else {
                    $('#addModal').find('.hour-privilege').html('');
                }
                var overdue = privilege + otherConsume - receipt;
                overdue = overdue < 0 ? 0 : overdue;
                $('#addModal').find('.hour-total').html(parseFloat(total + otherConsume).toFixed(2));
                $('#addModal').find('.hour-receipt').html(receipt.toFixed(2));
                $('#addModal').find('.hour-deposit').html(deposit.toFixed(2));
                $('#addModal').find('.hour-overdue').html(overdue.toFixed(2));            
            });              
        }, null);          
    };
    //长租房
    var calculateAddLongReceiveTotal = function() {
        var total = 0;
        var longs = 0;
        $('#addOrderLongRoom .addOrderLongPrice').each(function() {
            var val = $(this).val();
            if(val == '') {
                val = 0;
            }
            total += parseFloat(val);
            longs += parseInt($(this).closest('.addOrderLongRoomTr').find('.addOrderRoomLong .info').text());
        });
        var privilege = total;
        var receipt = 0;
        var deposit = 0;
        var otherConsume = 0;
        var receivearr = [];
        $('#addOrderLongReceive .addOrderLongReceiveTr').each(function() {
            var isDeposit = $(this).find('.addOrderLongReceiveIsDeposit').data('value')
            var value = parseFloat($(this).find('.addOrderLongReceive').val());
            var type = $(this).find('.addOrderLongReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyLongType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });          
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            $.each(data.data.transData, function (key, value) {
                var isDeposit = value.isDeposit;
                var value = parseFloat(value.value);
                var type = value.type;
                value = value > 0 ? value : 0;
                if(isDeposit == 1) {
                    deposit += value;
                } else if(isDeposit == 0){
                    receipt += value;
                } else{
                    if(type !== 0){
                        receipt += value;
                    }
                    otherConsume += value;
                }  
                if(window.discountLongrule != '') {
                    if(parseFloat(window.discountLong) == 0) {
                        privilege = ((total * window.discountLongrule * 100) / 1000);
                    } else {
                        privilege = (parseFloat(total) - parseFloat(window.discountLongrule)*parseInt(longs));
                    }
                    if(privilege < 0) {
                        privilege = 0;
                    }
                    $('#addModal').find('.long-privilege').html(lang('privilege') +window.symbols+ parseFloat(privilege+ otherConsume).toFixed(2));
                } else {
                    $('#addModal').find('.long-privilege').html('');
                }
                var overdue = privilege + otherConsume - receipt;
                overdue = overdue < 0 ? 0 : overdue;
                $('#addModal').find('.long-total').html(parseFloat(total + otherConsume).toFixed(2));
                $('#addModal').find('.long-receipt').html(receipt.toFixed(2));
                $('#addModal').find('.long-deposit').html(deposit.toFixed(2));
                $('#addModal').find('.long-overdue').html(overdue.toFixed(2));     
            });              
        }, null);                  
    };    
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive').on('click','.other-expense-content>.list',function(e){
        calculateAddReceiveTotal();
        calculateAddHourReceiveTotal();
        calculateAddLongReceiveTotal();
    });    
    //切换房
    $('#isHourRoom').on('click', '.common-panel', function() {
        window.roomStyle = false;
        window.longStyle = false;
        $('#commonPanel').removeClass('hidden');
        $('#hourPanel').addClass('hidden');
        $('#longPanel').addClass('hidden');
        $('.common-room-foot').removeClass('hidden');
        $('.hour-room-foot').addClass('hidden');
        $('.long-room-foot').addClass('hidden');
        $(this).addClass('is-active').siblings('a').removeClass('is-active');
        $('.form-group').removeClass('has-error');
    });
    $('#isHourRoom').on('click', '.hour-panel', function() {
        window.roomStyle = true;
        window.longStyle = false;
        $('#hourPanel').removeClass('hidden');
        $('#commonPanel').addClass('hidden');
        $('#longPanel').addClass('hidden');
        $('.common-room-foot').addClass('hidden');
        $('.hour-room-foot').removeClass('hidden');
        $('.long-room-foot').addClass('hidden');
        $(this).addClass('is-active').siblings('a').removeClass('is-active');
        $('.form-group').removeClass('has-error');
    });
    $('#isHourRoom').on('click', '.long-panel', function() {
        window.roomStyle = false;
        window.longStyle = true;
        $('#longPanel').removeClass('hidden');
        $('#hourPanel').addClass('hidden');
        $('#commonPanel').addClass('hidden');
        $('.long-room-foot').removeClass('hidden');
        $('.common-room-foot').addClass('hidden');
        $('.hour-room-foot').addClass('hidden');
        $(this).addClass('is-active').siblings('a').removeClass('is-active');
        $('.form-group').removeClass('has-error');
    });
    // 收款或者押金变化
    $('#addOrderReceive').on('blur', '.addOrderReceive', function() {
        calculateAddReceiveTotal();
    });
    $('#addOrderRoom').on('blur', '.addOrderPrice', function() {
        calculateAddReceiveTotal();
    });
    $('#addOrderHourReceive').on('blur', '.addOrderHourReceive', function() {
        calculateAddHourReceiveTotal();
    });
    $('#addOrderHourRoom').on('blur', '.addOrderHourPrice', function() {
        calculateAddHourReceiveTotal();
    });
    $('#addOrderLongReceive').on('blur', '.addOrderLongReceive', function() {
        calculateAddLongReceiveTotal();
    });
    $('#addOrderLongRoom').on('blur', '.addOrderLongPrice', function() {
        calculateAddLongReceiveTotal();
    });
    // 添加入住
    $('#addRoom').on('click', function(e) {
        e.preventDefault();
        var roomId = $('#addModal').data('roomId');
        var selectedDateFormat = $('#addModal').data('selectedDateFormat');
        var selectedDate = getDate(selectedDateFormat);
        $('#addOrderRoom').append(createAddRoomTemplate(roomId, selectedDate, selectedDateFormat));
        calculateAddReceiveTotal();
    });
    // 添加钟点房入住
    $('#addHourRoom').on('click', function(e) {
        e.preventDefault();
        var roomId = $('#addModal').data('roomId');
        var selectedDateFormat = $('#addModal').data('selectedDateFormat');
        var selectedDate = getDate(selectedDateFormat);
        $('#addOrderHourRoom').append(createAddHourRoomTemplate(roomId, selectedDate, selectedDateFormat));
        calculateAddHourReceiveTotal();
    });
    // 添加长租房入住
    $('#addLongRoom').on('click', function(e) {
        e.preventDefault();
        var roomId = $('#addModal').data('roomId');
        var selectedDateFormat = $('#addModal').data('selectedDateFormat');
        var selectedDate = getDate(selectedDateFormat);
        $('#addOrderLongRoom').append(createAddLongRoomTemplate(roomId, selectedDate, selectedDateFormat));
        calculateAddLongReceiveTotal();
    });
    // 去除入住
    $('#addModal').on('click', '.priceRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('table');
        var addUserRow = table.next('div.row');
        addUserRow.remove();
        table.remove();
        calculateAddReceiveTotal();
    });
    $('#addModal').on('click', '.priceHourRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('table');
        var addUserRow = table.next('div.row');
        addUserRow.remove();
        table.remove();
        calculateAddHourReceiveTotal();
    });
    $('#addModal').on('click', '.priceLongRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('table');
        var addUserRow = table.next('div.row');
        addUserRow.remove();
        table.remove();
        calculateAddLongReceiveTotal();
    });
    // 去除入住
    $('#addModal').on('click', '.userRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('tr.addOrderUserTr').remove();
    });
    $('#addModal').on('click', '.userHourRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('tr.addOrderHourUserTr').remove();
    });
    $('#addModal').on('click', '.userLongRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('tr.addOrderLongUserTr').remove();
    });
    // 添加收款
    $('#addReceipt').on('click', function(e) {
        e.preventDefault();
        $('#addOrderReceive tbody').append(createAddReceiveTemplate());
    });
    // 添加钟点房收款
    $('#addHourReceipt').on('click', function(e) {
        e.preventDefault();
        $('#addOrderHourReceive tbody').append(createAddHourReceiveTemplate());
    });
    // 添加长租房收款
    $('#addLongReceipt').on('click', function(e) {
        e.preventDefault();
        $('#addOrderLongReceive tbody').append(createAddLongReceiveTemplate());
    });
    // 去除收款
    $('#addModal').on('click', '.receiveRemove', function(e) {
        e.preventDefault();
        var tr = $(this).parents('tr');
        tr.remove();
        calculateAddReceiveTotal();
    });
    $('#addModal').on('click', '.receiveHourRemove', function(e) {
        e.preventDefault();
        var tr = $(this).parents('tr');
        tr.remove();
        calculateAddHourReceiveTotal();
    });
    $('#addModal').on('click', '.receiveLongRemove', function(e) {
        e.preventDefault();
        var tr = $(this).parents('tr');
        tr.remove();
        calculateAddLongReceiveTotal();
    });
    // 点击添加订单的下拉框
    $('#addModal').on('click', '.dropdown-menu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var toggle = liItem.parents('.dropdown-menu').siblings('[data-toggle="dropdown"]');
        liItem.addClass('active');
        liItem.siblings().removeClass('active');
        var value = liItem.data('value');
        var name = item.text();
        toggle.data('value', value);
        toggle.find('.info').html(name);
        if(window.roomStyle){  
            if(!(liItem.hasClass('addHourLi'))){
                calculateAddHourReceiveTotal();
            }
        }else if(window.longStyle){
            if(!(liItem.hasClass('addlongLi'))){
                calculateAddLongReceiveTotal();
            }
        }else{
            if(!(liItem.hasClass('addLi'))){
                calculateAddReceiveTotal();
            }   
        }

    });
    // 添加入住人
    $('#addModal').on('click', '.addUser', function(e) {
        var userTemplate = $($('#templateAddOrderUser').clone().html());
        var me = $(this);
        var table = me.parents('div.row').prev('table.table.addOrderTable.addOrderTableRoom');
        table.find('tbody').append(userTemplate);
    });
    $('#addModal').on('click', '.addHourUser', function(e) {
        var userTemplate = $($('#templateAddOrderHourUser').clone().html());
        var me = $(this);
        var table = me.parents('div.row').prev('table.table.addOrderHourTable.addOrderHourTableRoom');
        table.find('tbody').append(userTemplate);
    });
    $('#addModal').on('click', '.addLongUser', function(e) {
        var userTemplate = $($('#templateAddOrderLongUser').clone().html());
        var me = $(this);
        var table = me.parents('div.row').prev('table.table.addOrderLongTable.addOrderLongTableRoom');
        table.find('tbody').append(userTemplate);
    });
    // 房间切换计算价格
    $('#addOrderRoom').on('click', '.addOrderRoomIdMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var itemValue = liItem.data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var date = parentTr.find('.addOrderRoomCheckIn').data('value');
        var night = parentTr.find('.addOrderRoomNight').data('value');
        parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, itemValue, night));
    });
    // 钟点房切换计算价格
    $('#addOrderHourRoom').on('click', '.addOrderHourRoomIdMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var itemValue = liItem.data('value');
        var parentTr = item.parents('.addOrderHourRoomTr');
        var date = parentTr.find('.addOrderHourRoomCheckIn').data('time');
        var hour = parentTr.find('.addOrderRoomHour').data('value');
        parentTr.find('.addOrderHourPrice').val(calculateHourRoomPrice(date, itemValue, hour));
    });
    // 长租房切换计算价格
    $('#addOrderLongRoom').on('click', '.addOrderLongRoomIdMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var itemValue = liItem.data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var date = parentTr.find('.addOrderLongRoomCheckIn').data('value');
        var longs = parentTr.find('.addOrderRoomLong').data('value');
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, itemValue, longs));
    });
    //入住晚数切换计算价格
    $('#addOrderRoom').on('click', '.addOrderRoomNightMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var night = liItem.data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var date = parentTr.find('.addOrderRoomCheckIn').data('value');
        var room = parentTr.find('.addOrderRoomId').data('value');
        parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, room, night));
    });
    //入住钟点切换计算价格
    $('#addOrderHourRoom').on('click', '.addOrderRoomHourMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var hour = liItem.data('value');
        var parentTr = item.parents('.addOrderHourRoomTr');
        var date = parentTr.find('.addOrderHourRoomCheckIn').data('time');
        var room = parentTr.find('.addOrderHourRoomId').data('value');
        parentTr.find('.addOrderHourPrice').val(calculateHourRoomPrice(date, room, hour));
    });
    //入住月数切换计算价格
    $('#addOrderLongRoom').on('click', '.addOrderRoomLongMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var hour = liItem.data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var date = parentTr.find('.addOrderLongRoomCheckIn').data('value');
        var room = parentTr.find('.addOrderLongRoomId').data('value');
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, room, hour));
    });
    //入住日期切换计算价格
    $('#addOrderRoom').on('click', '.addOrderRoomCheckInMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var date = liItem.data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var room = parentTr.find('.addOrderRoomId').data('value');
        var night = parentTr.find('.addOrderRoomNight').data('value');
        parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, room, night));
    });
    //长租房入住日期切换计算价格
    $('#addOrderLongRoom').on('click', '.addOrderLongRoomCheckInMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var date = liItem.data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var room = parentTr.find('.addOrderLongRoomId').data('value');
        var longs = parentTr.find('.addOrderRoomLong').data('value');
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, room, longs));
    });
    // 录入订单的时候修改首个日期
    $('#addModal').on('click', '.addOrderTableRoom:first-child .addOrderRoomCheckInMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var value = liItem.data('value');
        var days = getDate(value).getDays(today);
        var addModal = $('#addModal');
        var roomId = addModal.find('.addOrderTableRoom:first-child .addOrderRoomId').data('value');
        var daysType = addModal.data('daysType');
        if(days === 0 || daysType === 0) {
            if(daysType !== days) {
                initAddOrderModal(roomId, value);
            }    
        } else {
            var diff = (daysType ^ days) >= 0;
            if(!diff) {
                initAddOrderModal(roomId, value);
            }
        }
    });
    
    $('#addModal').on('click', '.addOrderLongTableRoom:first-child .addOrderLongRoomCheckInMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var value = liItem.data('value');
        var days = getDate(value).getDays(today);
        var addModal = $('#addModal');
        var roomId = addModal.find('.addOrderLongTableRoom:first-child .addOrderLongRoomId').data('value');
        var daysType = addModal.data('daysType');
        if(days === 0 || daysType === 0) {
            if(daysType !== days) {
                initAddOrderModal(roomId, value);
            }
        } else {
            var diff = (daysType ^ days) >= 0;
            if(!diff) {
                initAddOrderModal(roomId, value);
            }
        }
    });
    // =============== ajax提交录入订单以及前端校验 =================
    var inputOrderCommonValidate = [{
            query: '.orderUserName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.Reservation')
        },
        {
            query: '.addOrderPrice',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('tip.room')
        },
        {
            query: '.addOrderReceive',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.payNull')
        },
        {
            query: '#bookRemark',
            regexp: window.commonRegexp.nameLength255,
            required: false,
            message: lang('tip.remark255')
        }
    ];
    var inputOrderHourCommonValidate = [{
            query: '.orderHourUserName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.Reservation')
        },
        {
            query: '.addOrderHourPrice',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('tip.room')
        },
        {
            query: '.addOrderHourReceive',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.payNull')
        },
        {
            query: '#bookHourRemark',
            regexp: window.commonRegexp.nameLength255,
            required: false,
            message: lang('tip.remark255')
        }
    ];
    var inputOrderLongCommonValidate = [{
            query: '.orderLongUserName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.Reservation')
        },
        {
            query: '.addOrderLongPrice',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('tip.room')
        },
        {
            query: '.addOrderLongReceive',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.payNull')
        },
        {
            query: '#bookLongRemark',
            regexp: window.commonRegexp.nameLength255,
            required: false,
            message: lang('tip.remark255')
        }
    ];
    //验证表单内容
    $('#addModal').inputValidate({
        submit: {
            query: '#submitBook'
        },
        inputs: inputOrderCommonValidate
    });
    $('#addModal .modal-content').inputValidate({
        submit: {
            query: '#submitCheckIn'
        },
        inputs: inputOrderCommonValidate
    });
    $('#addModal .modal-dialog').inputValidate({
        submit: {
            query: '#submitBookOld'
        },
        inputs: inputOrderCommonValidate
    });
    $('#hourPanel').inputValidate({
        submit: {
            query: '#submitHourBook'
        },
        inputs: inputOrderHourCommonValidate
    });
    $('#hourPanel .modal-body').inputValidate({
        submit: {
            query: '#submitHourCheckIn'
        },
        inputs: inputOrderHourCommonValidate
    });
    $('#hourPanel .form-horizontal').inputValidate({
        submit: {
            query: '#submitHourBookOld'
        },
        inputs: inputOrderHourCommonValidate
    });
    $('#longPanel').inputValidate({
        submit: {
            query: '#submitLongBook'
        },
        inputs: inputOrderLongCommonValidate
    });
    $('#longPanel .modal-body').inputValidate({
        submit: {
            query: '#submitLongCheckIn'
        },
        inputs: inputOrderLongCommonValidate
    });
    $('#longPanel .form-horizontal').inputValidate({
        submit: {
            query: '#submitLongBookOld'
        },
        inputs: inputOrderLongCommonValidate
    });

    //提交订单
    $('#submitBook').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getOrderParams();
        if(!getRoomVerification(1,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/add', params, 'post', createOrderSuccess, createOrderError, $(this));
    });   
    //直接入住
    $('#submitCheckIn').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var editZjrzButton = $(this);
        var params = getOrderParams();
        params.checkIn = 1;
        if(!getRoomVerification(1,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/orderCheckIn', params, 'post',createOrderSuccess, createOrderError, $(this));
    });
    //补录订单
    $('#submitBookOld').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getOrderParams();
        if(!getRoomVerification(1,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/orderOld', params, 'post', createOrderSuccess, createOrderError, $(this));
    });
    //钟点房提交订单
    $('#submitHourBook').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getHourOrderParams();
        if(!getRoomVerification(2,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/add', params, 'post', createOrderSuccess, createOrderError, $(this));
    });
    //钟点房直接入住
    $('#submitHourCheckIn').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var editHourZjrzButton = $(this);
        var params = getHourOrderParams();
        params.checkIn = 1;
        if(!getRoomVerification(2,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            if(window.timeTip){
                var confirmPass = window.confirm( lang('noneToTime')+'\r\n'+lang('tip.nonePay'));
            }else{
                var confirmPass = window.confirm(lang('tip.nonePay'));
            }
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }else{
            if(window.timeTip){
                var confirmPass = window.confirm(lang('noneToTime'));
                if(!confirmPass) {
                    hideMainLoading();
                    return false;
                }   
            }         
        }
        showMainLoading();
        ajaxRequest('/Home/Order/orderCheckIn', params, 'post',createOrderSuccess, createOrderError, $(this));
    });
    //钟点房补录订单
    $('#submitHourBookOld').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getHourOrderParams();
        if(!getRoomVerification(2,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/orderOld', params, 'post', createOrderSuccess, createOrderError, $(this));
    }); 
    //长租房提交订单
    $('#submitLongBook').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getLongOrderParams();
        if(!getRoomVerification(3,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/add', params, 'post', createOrderSuccess, createOrderError, $(this));
    });
    //长租房直接入住
    $('#submitLongCheckIn').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var editLongZjrzButton = $(this);
        var params = getLongOrderParams();
        params.checkIn = 1;    
        if(!getRoomVerification(3,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }    
        showMainLoading();
        ajaxRequest('/Home/Order/orderCheckIn', params, 'post',createOrderSuccess, createOrderError, $(this));
    });
    //长租房补录订单
    $('#submitLongBookOld').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var params = getLongOrderParams();
        if(!getRoomVerification(3,params,$(this))){
            return false;
        }
        if(params.hasReceive === false) {
            var confirmPass = window.confirm(lang('tip.nonePay'));
            if(!confirmPass) {
                hideMainLoading();
                return false;
            }
        }
        showMainLoading();
        ajaxRequest('/Home/Order/orderOld', params, 'post', createOrderSuccess, createOrderError, $(this));
    });    
    var getOrderParams = function() {
        //验证数据
        var params = {};
        params.hotel = window.currentHotel;
        params.bookname = $('#bookName').val();
        params.channel = $('.addOrderChannel').data('value');
        params.bookmobile = $('#bookMobile').val();
        params.identity = $('#bookIdentity').val();
        params.detail = [];
        $('#addModal').find('.addOrderTableRoom').each(function() {
            var orderdetail = {};
            var me = $(this);
            orderdetail.orderDate = me.find('.addOrderRoomCheckIn').data('value');
            orderdetail.roomId = me.find('.addOrderRoomId').data('value');
            orderdetail.nights = me.find('.addOrderRoomNight').data('value');
            orderdetail.payment = parseFloat(me.find('.addOrderPrice').val());
            orderdetail.users = [];
            me.find('.addOrderUserTr').each(function() {
                var orderUserItem = {};
                var orderUser = $(this);
                orderUserItem.name = orderUser.find('.orderUserName').val();
                var mobile = orderUser.find('.orderUserMobile').val();
                if(mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                var areaCode = orderUser.find('.areaCodeValue').text().trim();
                if (areaCode !== '') {
                  orderUserItem.areaCode = areaCode;
                }
                var identity = orderUser.find('.orderUserID').val();
                if(identity !== '') {
                    orderUserItem.identity = identity;
                }
                orderdetail.users.push(orderUserItem);
            });
            params.detail.push(orderdetail);
        });
        params.remark = $('#bookRemark').val();
        params.receive = [];
        params.hasReceive = false;
        $('#addOrderReceive').find('.addOrderReceiveTr').each(function() {
            var money = {};
            money.category = $(this).find('.addOrderReceiveIsDeposit').data('value');
            money.type = $(this).find('.addOrderReceiveType').data('value');
            money.transCurrencyId = $(this).find('.addMultiCurrencyType').data('value');
            var moneyCount = $(this).find('.addOrderReceive').val();
            if(moneyCount === '') {
                money.value = 0;
            } else {
                money.value = parseFloat(moneyCount);
            }
            params.receive.push(money);
            // 检测是否有任何收款，押金不算收款
            if(params.hasReceive === false && money.category === 0 && money.value > 0) {
                params.hasReceive = true;
            }
        });
        //计算押金
        var total = 0;
        var reducePrice = 0;
        //计算应付金额
        $('#addOrderRoom').find('.addOrderPrice').each(function() {
            total += parseFloat($(this).val());
            reducePrice += parseFloat(window.discountrule)*parseInt($(this).closest('.addOrderTableRoom').find('.nights .info').text());
        });
        var privilege = 0;
        if(window.discountrule != '') {
            var vip = {
                'orig': total,
                'discount': window.discount,
                'discountRule': window.discountrule
            };
            if(parseInt(window.discount) == 0) {
                privilege = ((total * window.discountrule * 100) / 1000);
            } else {
                privilege = (parseFloat(total) - reducePrice);
            }
            if(privilege < 0) {
                privilege = 0;
            }
            params.payment = privilege;
            params.vip = vip;
        } else {
            params.payment = total;
        }
        return params;
    };
    //钟点房
    var getHourOrderParams = function() {
        //验证数据
        var params = {};
        params.hotel = window.currentHotel;
        params.bookname = $('#bookName').val();
        params.channel = $('.addOrderChannel').data('value');
        params.bookmobile = $('#bookMobile').val();
        params.identity = $('#bookIdentity').val();
        params.detail = [];
        window.timeTip = false;
        $('#addModal').find('.addOrderHourTableRoom').each(function() {
            var orderdetail = {};
            var me = $(this);
            var hour_min = me.find('.addOrderHourRoomCheckIn .info').text();
            var orderDate = me.find('.addOrderHourRoomCheckIn').data('time')+' '+hour_min+':00';
            if(parseInt(hour_min) < (parseInt(window.presenttime))){
                window.timeTip = true;
            }else{
                window.timeTip = false;
            }
            orderdetail.orderDate = orderDate;
            orderdetail.roomId = me.find('.addOrderHourRoomId').data('value');
            orderdetail.nights = 0;
            orderdetail.hour = me.find('.addOrderRoomHour').data('value');
            orderdetail.payment = parseFloat(me.find('.addOrderHourPrice').val());
            orderdetail.users = [];
            me.find('.addOrderHourUserTr').each(function() {
                var orderUserItem = {};
                var orderUser = $(this);
                orderUserItem.name = orderUser.find('.orderHourUserName').val();
                var mobile = orderUser.find('.orderHourUserMobile').val();
                if(mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                var areaCode = orderUser.find('.areaCodeValue').text().trim();
                if (areaCode !== '') {
                  orderUserItem.areaCode = areaCode;
                }
                var identity = orderUser.find('.orderHourUserID').val();
                if(identity !== '') {
                    orderUserItem.identity = identity;
                }
                orderdetail.users.push(orderUserItem);
            });
            params.detail.push(orderdetail);
        });
        params.remark = $('#bookHourRemark').val();
        params.receive = [];
        params.hasReceive = false;
        $('#addOrderHourReceive').find('.addOrderHourReceiveTr').each(function() {
            var money = {};
            money.category = $(this).find('.addOrderHourReceiveIsDeposit').data('value');
            money.type = $(this).find('.addOrderHourReceiveType').data('value');
            money.transCurrencyId = $(this).find('.addMultiCurrencyHourType').data('value');
            var moneyCount = $(this).find('.addOrderHourReceive').val();
            if(moneyCount === '') {
                money.value = 0;
            } else {
                money.value = parseFloat(moneyCount);
            }
            params.receive.push(money);
            // 检测是否有任何收款，押金不算收款
            if(params.hasReceive === false && money.category === 0 && money.value > 0) {
                params.hasReceive = true;
            }
        });
        //计算押金
        var total = 0;
        var reducePrice = 0;
        //计算应付金额
        var subtract = 0;
        $('#addOrderHourRoom').find('.addOrderHourPrice').each(function() {
            total += parseFloat($(this).val());
            subtract++;
        });
        var privilege = 0;
        if(window.discountHourrule != '') {
            var vip = {
                'orig': total,
                'discount': window.discountHour,
                'discountRule': window.discountHourrule
            };
            if(parseInt(window.discountHour) == 0) {
                privilege = ((total * window.discountHourrule * 100) / 1000);
            } else {
                privilege = (parseFloat(total) - parseFloat(window.discountHourrule)*parseInt(subtract));
            }
            if(privilege < 0) {
                privilege = 0;
            }
            params.payment = privilege;
            params.vip = vip;
        } else {
            params.payment = total;
        }
        return params;
    };    
    //长租房
    var getLongOrderParams = function() {
        //验证数据
        var params = {};
        params.hotel = window.currentHotel;
        params.bookname = $('#bookName').val();
        params.channel = $('.addOrderChannel').data('value');
        params.bookmobile = $('#bookMobile').val();
        params.identity = $('#bookIdentity').val();
        params.detail = [];
        $('#addModal').find('.addOrderLongTableRoom').each(function() {
            var orderdetail = {};
            var me = $(this);
            orderdetail.orderDate = me.find('.addOrderLongRoomCheckIn').data('value');
            orderdetail.roomId = me.find('.addOrderLongRoomId').data('value');
            orderdetail.month = me.find('.addOrderRoomLong').data('value');
            orderdetail.nights = 0;
            orderdetail.payment = parseFloat(me.find('.addOrderLongPrice').val());
            orderdetail.users = [];
            me.find('.addOrderLongUserTr').each(function() {
                var orderUserItem = {};
                var orderUser = $(this);
                orderUserItem.name = orderUser.find('.orderLongUserName').val();
                var mobile = orderUser.find('.orderLongUserMobile').val();
                if(mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                var areaCode = orderUser.find('.areaCodeValue').text().trim();
                if (areaCode !== '') {
                  orderUserItem.areaCode = areaCode;
                }
                var identity = orderUser.find('.orderLongUserID').val();
                
                if(identity !== '') {
                    orderUserItem.identity = identity;
                }
                orderdetail.users.push(orderUserItem);
            });
            params.detail.push(orderdetail);
        });
        params.remark = $('#bookRemark').val();
        params.receive = [];
        params.hasReceive = false;
        $('#addOrderLongReceive').find('.addOrderLongReceiveTr').each(function() {
            var money = {};
            money.category = $(this).find('.addOrderLongReceiveIsDeposit').data('value');
            money.type = $(this).find('.addOrderLongReceiveType').data('value');
            money.transCurrencyId = $(this).find('.addMultiCurrencyLongType').data('value');
            var moneyCount = $(this).find('.addOrderLongReceive').val();
            if(moneyCount === '') {
                money.value = 0;
            } else {
                money.value = parseFloat(moneyCount);
            }
            params.receive.push(money);
            // 检测是否有任何收款，押金不算收款
            if(params.hasReceive === false && money.category === 0 && money.value > 0) {
                params.hasReceive = true;
            }
        });
        //计算押金
        var total = 0;
        var reducePrice = 0;
        //计算应付金额
        $('#addOrderLongRoom').find('.addOrderLongPrice').each(function() {
            total += parseFloat($(this).val());
            reducePrice += parseFloat(window.discountLongrule)*parseInt($(this).closest('.addOrderLongTableRoom').find('.addOrderRoomLong .info').text());
        });
        var privilege = 0;
        if(window.discountLongrule != '') {
            var vip = {
                'orig': total,
                'discount': window.discountLong,
                'discountRule': window.discountLongrule
            };
            if(parseInt(window.discountLong) == 0) {
                privilege = ((total * window.discountLongrule * 100) / 1000);
            } else {
                privilege = (parseFloat(total) - reducePrice);
            }
            if(privilege < 0) {
                privilege = 0;
            }
            params.payment = privilege;
            params.vip = vip;
        } else {
            params.payment = total;
        }
        return params;        
    };     
    // 打印设置
    $('#printSettingModal').on('show.bs.modal', function(e) {
        paramstart = {};
        paramstart.hotel = window.currentHotel;
        paramstart.printType = 1;
        ajaxRequest('/Home/PrintSetting/getSetting', paramstart, 'post', function(data) {
            var info = data.data;
            var checkoutprint = info.checkoutprint;
            var preview = info.preview;
            var printername = info.printername;
            var printerpaper = info.printerpaper;
            var printidentity = info.printidentity;
            var printmobile = info.printmobile;
            var printtimes = info.printtimes;
            var tips1 = info.tips1;
            var tips2 = info.tips2;
            info
            if(printerpaper == 'A4'){
                $('#requestPrintA4').attr('checked',true).closest('label').addClass('is-checked');
            }else if(printerpaper == 'X58'){
                $('#requestPrintX58').attr('checked',true).closest('label').addClass('is-checked');
            }
            if(printtimes == 1){
                $('#requestPrintUnite').attr('checked',true).closest('label').addClass('is-checked');
            }else{
                $('#requestPrintTwoUnite').attr('checked',true).closest('label').addClass('is-checked');
            }        
            checkoutprint == 1 ? $('#isPrintTip').addClass('is-checked') : $('#isPrintTip').removeClass('is-checked');
            preview == 1 ? $('#isPreviews').addClass('is-checked') : $('#isPreviews').removeClass('is-checked');
            printmobile == 1 ? $('#isPrintMoblie').addClass('is-checked') : $('#isPrintMoblie').removeClass('is-checked');
            printidentity == 1 ? $('#isPrintIDCard').addClass('is-checked') : $('#isPrintIDCard').removeClass('is-checked');
            $('#printName').val(printername);
            $('#printHint3').val(tips1);
            $('#printHint4').val(tips2);        
        }, function(error) {
            
        });
        paramCard = {};
        paramCard.hotel = window.currentHotel;
        paramCard.printType = 2;
        ajaxRequest('/Home/PrintSetting/getSetting', paramCard, 'post', function(data) {
            var info = data.data;
            var printername = info.printername;
            var tips1 = info.tips1;
            var tips2 = info.tips2;
            $('#printNameCard').val(printername);
            $('#printHint1').val(tips1);
            $('#printHint2').val(tips2);        
        }, function(error) {
            
        });  
    });

    $('#requestPrintOrder').on('click', function() {
        $('#container-order').removeClass('hidden');
        $('#container-card').addClass('hidden');
        $('#submitPrintHintOrder').removeClass('hidden');
        $('#submitPrintHintCard').addClass('hidden');
    });
    $('#requestPrintCard').on('click', function() {
        $('#container-order').addClass('hidden');
        $('#container-card').removeClass('hidden');
        $('#submitPrintHintOrder').addClass('hidden');
        $('#submitPrintHintCard').removeClass('hidden');
    });
    $('#printSettingModal').inputValidate({
        submit: {
            query: '#submitPrintHintCard'
        },
        inputs: [{
            query: '#printHint1',
            regexp: /^.{0,30}$/,
            message: '友情提示不能超过30个字'
        }, {
            query: '#printHint2',
            regexp: /^.{0,30}$/,
            message: '友情提示不能超过30个字'
        }]
    });
    //房卡
    $('#submitPrintHintCard').on('successSubmit.amos.inputValidate', function(e) {
        var submitBtn = $(this);
        var printHint1 = $('#printHint1').val();
        var printHint2 = $('#printHint2').val();
        var printNameCard = $('#printNameCard').val();
        var params = {};
        params.hotel = window.currentHotel;
        params.printType = 2;
        params.printername = printNameCard;
        params.tips1 = printHint1;
        params.tips2 = printHint2;
        saveSettings(params, submitBtn);
    });
    //订单
    $('#submitPrintHintOrder').on('click', function(e) {
        var submitBtn = $(this);
        var isUnite = $('#requestPrintUnite').prop('checked');
        var unite = '';
        isUnite == true ? unite = 1 : unite = 2;
        var isPaper = $('#requestPrintA4').prop('checked');
        var paper = ''
        isPaper == true ? paper = 'A4' : paper = 'X58';
        var isPreviews = $('#isPreviews').find('input[type=checkbox]').prop('checked');
        var previews = '';
        isPreviews == true ? previews = 1 : previews = 0;
        var isMoblie = $('#isPrintMoblie').find('input[type=checkbox]').prop('checked');
        var moblie = '';
        isMoblie == true ? moblie = 1 : moblie = 0;
        var isCard = $('#isPrintIDCard').find('input[type=checkbox]').prop('checked');
        var card = '';
        isCard == true ? card = 1 : card = 0;
        var isTip = $('#isPrintTip').find('input[type=checkbox]').prop('checked');
        var tip = '';
        isTip == true ? tip = 1 : tip = 0;
        var printName = $('#printName').val();
        var printHint3 = $('#printHint3').val();
        var printHint4 = $('#printHint4').val();
        var params = {};
        params.hotel = window.currentHotel;
        params.printType = 1;
        params.preview = previews;
        params.printtimes = unite;
        params.printername = printName;
        params.tips1 = printHint3;
        params.tips2 = printHint4;
        params.printmobile = moblie;
        params.printidentity = card;
        params.printerpaper = paper;
        params.checkoutprint = tip;
        saveSettings(params, submitBtn);
    });
    var saveSettings = function(params, submitBtn) {
        var saveUrl = '';
        if(params.printType==1)
        {
            saveUrl = '/Home/PrintSetting/saveOrderSetting';
        }
        else if(params.printType==2)
        {
            saveUrl = '/Home/PrintSetting/saveQrcodeSetting';
        }
        ajaxRequest(saveUrl, params, 'post', function(data) {
            formInlineTip(submitBtn,lang('successfullySave'), 2);
            $('#printSettingModal').modal('hide');
        }, null, submitBtn);
    }
    //验证会员卡
    var confirmVIPcardInfo = $('#confirmVIPcardInfo');
    var memberInfoModal = $('#memberInfoModal');
    var getMembershipVerification = function(info,submitTrigger,params){
        var orderparams = params;
        $('#getvipmobile').data('submitTrigger',submitTrigger);
        $('#getvipmobile').data('params',params);
        confirmVIPcardInfo.data('submitTrigger',submitTrigger);
        memberInfoModal.find('.card-username').text('');
        memberInfoModal.find('.card-grade').text('');
        memberInfoModal.find('.card-balance').text('');
        memberInfoModal.find('.card-charge').text('');
        memberInfoModal.find('#getvipmobile').val('');
        var testGetCode = $('.test-get-code');
        var param = {};
        var vipCard = {};
        vipCard.cardMobile = info.mobile;
        vipCard.cardAreaCode = info.areaCode;
        param.hotel = window.currentHotel;
        param.mobile = info.mobile;
        param.areaCode = info.areaCode;
        ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
            if(data.data.length != 0){
                confirmVIPcardInfo.removeClass('disabled');
                testGetCode.removeClass('disabled');
                var vipinfo = data.data[0];
                memberInfoModal.find('.card-username').text(vipinfo.name);
                memberInfoModal.find('.card-grade').text(vipinfo.levelname);
                memberInfoModal.find('.card-balance').text(vipinfo.cardPrice);
                memberInfoModal.find('.card-charge').text(info.price.toFixed(2));
                memberInfoModal.find('.areaCodeValue').text(info.areaCode);
                memberInfoModal.find('#getvipmobile').val(vipinfo.mobile);
                orderparams.vipCard = vipCard; 
                confirmVIPcardInfo.data('orderparams',orderparams);
            }else{
                confirmVIPcardInfo.addClass('disabled');
                testGetCode.addClass('disabled');
            }
        }, function(data) {
            confirmVIPcardInfo.addClass('disabled');
            testGetCode.addClass('disabled');
        });        
        memberInfoModal.find('.form-group ').removeClass('has-error');
        memberInfoModal.modal('show');   
    }; 
    confirmVIPcardInfo.click(function(){
        var submitTrigger = $(this).data('submitTrigger');
        var orderparams = confirmVIPcardInfo.data('orderparams');
        var submitBtn = submitTrigger.attr('id');             
        if(!(submitBtn == 'editOrderConfirm' || submitBtn == 'checkInConfirm')){
            ajaxRequest('/Home/Order/verifyWithMobile', {
                "hotel": window.currentHotel,
                "vcode": $('#vipVerificationCode').val(),
            }, 'post', function(data) {
                if(submitBtn == 'submitBook' || submitBtn == 'submitHourBook' || submitBtn == 'submitLongBook'){
                    ajaxRequest('/Home/Order/add', orderparams, 'post', createOrderSuccess, createOrderError, submitTrigger);
                }else if(submitBtn == 'submitCheckIn' || submitBtn == 'submitHourCheckIn' || submitBtn == 'submitLongCheckIn'){
                    ajaxRequest('/Home/Order/orderCheckIn', orderparams, 'post',createOrderSuccess, createOrderError, submitTrigger);
                }else{
                    ajaxRequest('/Home/Order/orderOld', orderparams, 'post', createOrderSuccess, createOrderError, submitTrigger);
                }
                memberInfoModal.modal('hide');
            }, function(error) {
                if(typeof error.responseJSON == 'undefined') {
                    formInlineTip(confirmVIPcardInfo,lang('tip.networkPoor'), 0);
                } else {
                    formInlineTip(confirmVIPcardInfo, error.responseJSON.info, 0);
                }
            });             
        }
    });    
    $('.test-get-code').on('click',function(){
        var that = $(this);
        ajaxRequest('/Home/Order/sendMobile', {
            "hotel": window.currentHotel,
            "mobile": $('#getvipmobile').val(),
            "areaCode": $('#memberInfoModal').find('.areaCodeValue').text(),
        }, 'post', function(data) {
            timeDisplay(that, 60);
        }, function(error) {
            if(typeof error.responseJSON == 'undefined') {
                formInlineTip(confirmVIPcardInfo,lang('tip.networkPoor'), 0);
            } else {
                formInlineTip(confirmVIPcardInfo, error.responseJSON.info, 0);
            }
        });             
    });
    $('#getvipmobile').blur(function(){
        var submitTrigger = $(this).data('submitTrigger');
        var submitBtn = submitTrigger.attr('id');   
        if(!(submitBtn == 'editOrderConfirm' || submitBtn == 'checkInConfirm')){
            var memberInfoModal = $('#memberInfoModal');
            var info = {
                mobile:$(this).val(),
                areaCode:memberInfoModal.find('.areaCodeValue').text(),
                price:window.membershipMobile.price
            };         
            getMembershipVerification(info,submitTrigger,$(this).data('params'));            
        }

    }); 
    var getRoomVerification = function(status,params,that){
        var getVerification = false;
        var price = 0;
        if(status == 1){
            var receiveTr = $('#addOrderReceive .addOrderReceiveTr');
            var room = $('#addOrderRoom .addOrderTableRoom').eq(0).find('.addOrderUserTr').eq(0);
            var mobile = room.find('.orderUserMobile').val();
        }else if(status == 2){
            var receiveTr = $('#addOrderHourReceive .addOrderHourReceiveTr');
            var room = $('#addOrderHourRoom .addOrderHourTableRoom').eq(0).find('.addOrderHourUserTr').eq(0);
            var mobile = room.find('.orderHourUserMobile').val();
        }else{
            var receiveTr = $('#addOrderLongReceive .addOrderLongReceiveTr');
            var room = $('#addOrderLongRoom .addOrderLongTableRoom').eq(0).find('.addOrderLongUserTr').eq(0);
            var mobile = room.find('.orderLongUserMobile').val();
        }
        receiveTr.each(function() {
            var value = $(this).find('td').eq(1).find('.info').text();
            if(value == lang('recharge.8')){
                getVerification = true;
                var vipPrice = $(this).find('td').eq(3).find('input').val();
                if(vipPrice == ''){
                    vipPrice = 0;
                }
                price += parseFloat(vipPrice);
            }
        });  
        if(getVerification){
            if(mobile == ''){
                formInlineTip(that, lang('recharge.10'), 0);
            }else{
                var param = {};
                param.hotel = window.currentHotel;
                param.mobile = mobile;
                param.areaCode = room.find('.areaCodeValue').text();
                ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
                    if(data.data.length == 0){
                        formInlineTip(that, lang('recharge.11'), 0);
                    }else{
                        if(price>0){
                            window.membershipMobile = {
                                mobile:mobile,
                                areaCode:room.find('.areaCodeValue').text(),
                                price:price
                            };    
                            getMembershipVerification(window.membershipMobile,that,params);                              
                        }else{
                            formInlineTip(that, lang('recharge.12'), 0);
                        }
                    }
                }, function(data) {
                    formInlineTip(that, lang('recharge.11'), 0);
                });                 
            }; 
            return false;
        }else{
            return true;
        };
    }
    $('#rfReadInfoModal').on('show.bs.modal', function(e) {
        webSocketInit();
    });
    //读卡时类型切换
    $('#cardTypeRadio input:radio').change(function () {
        if ($('#requestMeizhuCardTypeBth').prop("checked")) {
            $('#issueMacGroup').removeClass('hidden');
            var macSelecter = $("#requestIssueMac");
            macSelecter.empty();
            if(!window.macList){
                ajaxRequest('/Home/Order/getBthDeviceList',{
                    "hotel" : window.currentHotel, 
                }, 'post', function(data){
                    window.macList = data.data.device;
                    window.deviceCommandForRead = data.data.readCommand;
                    window.deviceCommandForCancel = data.data.cancelCommand;
                    for(var i = 0; i < window.macList.length; i++) {
                        macSelecter.append('<option value="'+window.macList[i].mac+'">'+window.macList[i].mac+'</option>');
                    }
                }, function(error) {
                    modalAlert(error.responseJSON.info);
                });
            }else{
                for(var i = 0; i < window.macList.length; i++) {
                    macSelecter.append('<option value="'+window.macList[i].mac+'">'+window.macList[i].mac+'</option>');
                }
            }
        } else {
            $('#issueMacGroup').addClass('hidden');
        }
    });
});